import re

import django_filters
from django.db.models import Q

from app.health_manage.models import ServerHealth


class ServerHealthFilter(django_filters.FilterSet):
    """设备类出库过滤器"""
    systemSN = django_filters.CharFilter(method='multi_filter')
    manageIp = django_filters.CharFilter(field_name='manageIp', lookup_expr='icontains')
    ipmi = django_filters.CharFilter(field_name='ipmi', lookup_expr='exact')
    dataCenter = django_filters.CharFilter(field_name='dataCenter', lookup_expr='exact')
    userAccount = django_filters.CharFilter(field_name='userAccount', lookup_expr='exact')
    userProductLine = django_filters.CharFilter(field_name='userProductLine', lookup_expr='icontains')
    manu = django_filters.CharFilter(field_name='manu', lookup_expr='exact')
    model = django_filters.CharFilter(field_name='model', lookup_expr='exact')
    health = django_filters.CharFilter(field_name='health', lookup_expr='exact')
    lockStatus = django_filters.CharFilter(field_name='lockStatus', lookup_expr='exact')
    lifeTime = django_filters.CharFilter(field_name='lifeTime', lookup_expr='exact')
    isDeleted = django_filters.CharFilter(field_name='isDeleted', lookup_expr='exact')

    class Meta:
        model = ServerHealth
        fields = ['systemSN', 'manageIp', 'ipmi', 'dataCenter', 'userAccount',
                  'userProductLine', 'manu', 'model', 'health', 'lockStatus', 'lifeTime', 'isDeleted']

    def multi_filter(self, queryset, name, value):
        values = re.split(r'[\s,]+', value.strip()) if value else []

        # 使用 Q 对象来处理字符串和列表筛选
        q_objects = Q()
        for val in values:
            q_objects |= Q(**{f"{name}__exact": val})

        return queryset.filter(q_objects)
